/**
 * Copyright 2011 Mathieu Magnaudet
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package edu.enac.fileloader.ivylistener;

import java.util.ArrayList;
import java.util.List;

import fr.dgac.ivy.Ivy;
import fr.dgac.ivy.IvyClient;
import fr.dgac.ivy.IvyException;
import fr.dgac.ivy.IvyMessageListener;
import edu.enac.fileloader.exception.FileLoaderException;
import edu.enac.fileloader.util.Observable;
import edu.enac.fileloader.util.Observer;


public class IvyAgent implements Observable{
	private static final IvyAgent INSTANCE = new IvyAgent();
	private List<Observer> observers;
	private boolean isStarted = false;
	private Ivy bus;
	
	private IvyAgent() {
		observers = new ArrayList<Observer>();
	}
	
	public static IvyAgent getInstance() {
		return INSTANCE;
	}
	
	public void start() throws IvyException, FileLoaderException {
		if(isStarted) {
			throw new FileLoaderException("Ivy agent is already running");
		} 
		isStarted = true;
		bus = new Ivy("MessageListener", "MessageListener Ready", null);
		bus.bindMsg("new_file(.*)", new IvyMessageListener() {
			
			@Override
			public void receive(IvyClient arg0, String[] arg1) {
				StringBuffer buffer = new StringBuffer();
				for(String s: arg1) {
					buffer.append(s);
					notifyObservers(s);
					//System.out.println(s);
				}
				
			}
		});
		bus.start(null);
	}
	
	protected void notifyObservers(String s) {
		for(Observer obs: observers) {
			obs.update(this, s);
		}
	}

	public void stop() {
		bus.stop();
		isStarted = false;
	}

	/* (non-Javadoc)
	 * @see fr.enac.filereceiver.util.Observable#addObserver(fr.enac.filereceiver.util.Observer)
	 */
	@Override
	public void addObserver(Observer o) {
		observers.add(o);
	}

	/* (non-Javadoc)
	 * @see fr.enac.filereceiver.util.Observable#deleteObserver(fr.enac.filereceiver.util.Observer)
	 */
	@Override
	public void deleteObserver(Observer o) {
		observers.remove(o);
	}

	/* (non-Javadoc)
	 * @see fr.enac.filereceiver.util.Observable#deleteObservers()
	 */
	@Override
	public void deleteObservers() {
		observers.clear();

	}
}
